//
//  OtherSongerListViewController.m
//  DayByDay
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "OtherSongerListViewController.h"
#import "SongerListTableViewCell.h"
#import "OtherSongerListDataModel.h"
#import "OrderSongerListWithName.h"
#import "SongListDetailViewController.h"


@interface OtherSongerListViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)OtherSongerListDataModel *otherDataModel;
@property (nonatomic, strong)NSDictionary *dic;
@property (nonatomic, strong)NSMutableArray *myArray;

// 搜索专用



//@property(nonatomic,retain)NSMutableArray *searchArray;
//
//
//@property(nonatomic,retain)UISearchBar *mySearchBar;
//@property(nonatomic,retain)UISearchDisplayController *searchDC;
//
//@property(nonatomic,retain)UISearchController *searchController;
//
//@property (nonatomic, strong)

@end

@implementation OtherSongerListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.searchArray = [NSMutableArray array];
    [self createView];
    [self createData];
//    [self createSearchVC];
}

//- (void)createSearchVC {
//    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
//    self.searchController.searchResultsUpdater = self;
//    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
//    self.searchController.dimsBackgroundDuringPresentation = NO;
//    //设置点击搜索框时候隐藏导航栏
//    self.searchController.hidesNavigationBarDuringPresentation = NO;
//    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
//    //    [searchBar sizeToFit]:设置searchBar位置自适应
//    [self.searchController.searchBar sizeToFit];
//    self.tableView.tableHeaderView = self.searchController.searchBar;
////    self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
////    [self.HUB show:YES];
//}

- (void)createData {
    NSString *firstStr = @"http://api.dongting.com/song/singer_classify/";
    NSString *lastStr = @"?app=ttpod&v=v9.0.1.2016050614&user_id=0&mid=iPhone7%2C2&f=f320&s=s310&imsi=&hid=&splus=9.3.1&active=1&net=2&openudid=5e6106cc8d5bcf35f60a2997c79a00bb5a7c631f&idfa=ABDADD65-0877-4840-B14F-DFC8D1114AB0&utdid=VzR0dwnWYs8DANbYJ8SsFzOU&alf=(null)&bundle_id=com.ttpod.music&latitude=-1&longtitude=-1&access_token=(null)&vc=9000100";
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",firstStr,self.songerId,lastStr];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionConfiguration *configur = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configur];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            self.otherDataModel = [OtherSongerListDataModel new];
            [self.otherDataModel setValuesForKeysWithDictionary:[dic objectForKey:@"data"]];
          self.dic =[NSDictionary dictionaryWithDictionary: [OrderSongerListWithName sortWithArray:self.otherDataModel.singers]];
            self.myArray = [NSMutableArray arrayWithArray:[self.dic allKeys]];
            NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
            NSArray *descriptorArr = @[descriptor];
            [self.myArray sortUsingDescriptors:descriptorArr];
            [self.tableView reloadData];
        });
    }];
    [task resume];
}



- (void)createView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[SongerListTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SongerListTableViewCell class])];
    self.tableView.separatorStyle = 0;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SongListDetailViewController *songVC = [SongListDetailViewController new];
    if (indexPath.section == 0) {
        songVC.value = [[self.otherDataModel.hotSingers[indexPath.row] singerId] stringValue];;
        [self.navigationController pushViewController:songVC animated:YES];
    } else {
        NSString *str =[self.myArray objectAtIndex:(indexPath.section - 1)];
        NSArray *array = [self.dic objectForKey:str];
        OtherSongerListDataHotSingersModel *model = array[indexPath.row];
        songVC.value = [model.singerId stringValue];
        [self.navigationController pushViewController:songVC animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[self.dic allKeys] count] + 1;
}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.myArray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"热";
    } else {
        return [self.myArray objectAtIndex:(section - 1)];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.otherDataModel.hotSingers.count;
    } else {
        return [[self.dic valueForKey:[self.myArray objectAtIndex:section - 1]] count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SongerListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SongerListTableViewCell class])];
    if (indexPath.section == 0) {
        OtherSongerListDataHotSingersModel *model = nil;
//        if (self.searchController.active) {
//            
//            NSLog(@"选中搜索列表");
//            model = [self.searchArray objectAtIndex:indexPath.row];
//            
//        }
//        else {
//            
//            NSLog(@"选中所有列表");
//            model = self.otherDataModel.hotSingers[indexPath.row];
//            
//        }

        model = self.otherDataModel.hotSingers[indexPath.row];
        cell.model = model;
        cell.selectionStyle = 0;
        return cell;
    } else {
        NSString *str =[self.myArray objectAtIndex:(indexPath.section - 1)];
        NSArray *array = [self.dic objectForKey:str];
        OtherSongerListDataHotSingersModel *model = array[indexPath.row];
        cell.model = model;
        cell.selectionStyle = 0;
        return cell;
    }
    
    
}

// search 的协议方法.

//-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
//    
//    NSString *searchString = [self.searchController.searchBar text];
//    
//    NSLog(@"===%@",searchString);
//    
//    [self.searchArray removeAllObjects];
//    for (OtherSongerListDataHotSingersModel *model in self.myArray) {
//        
//        //rangeOfString:方法是在model中搜索是否包含searchText
//        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
//        //NSNotFound 表示请求操作的某个内容没有发现
//        if ([model.name rangeOfString:searchString].location != NSNotFound) {
//            
//            [self.searchArray addObject:model];
//        }
//    }
//    NSLog(@"searchArray===%@",self.searchArray);
//    
//    [self.tableView reloadData];
//    
//}
//
////UISearchController的移除
////在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
//- (void)viewWillDisappear:(BOOL)animated {
//    
//    [super viewWillDisappear:animated];
//    
//    if (self.searchController.active) {
//        
//        self.searchController.active = NO;
//        [self.searchController.searchBar removeFromSuperview];
//        
//    }
//}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
